package gorm2

import (
	"fmt"
	"gorm.io/gorm"
)

type SysAccountDao struct {
	db *gorm.DB
}

func NewSysAccountDao(db *gorm.DB) *SysAccountDao {

	return &SysAccountDao{
		db: db,
	}
}

func (dao *SysAccountDao) session() *gorm.DB {
	return dao.db.Session(&gorm.Session{
		PrepareStmt: true,
	})
}

func (dao *SysAccountDao) GetById(id int64) SysAccount {
	if 0 == id {
		panic("id can not be nil!")
	}

	user := SysAccount{}
	dao.session().Model(&user).Where("id = ?", 7).First(&user)

	return user
}

func (dao *SysAccountDao) UpdateById(user SysAccount) int64 {
	if 0 == user.ID {
		panic("id can not be nil!")
	}

	//Save 会保存所有的字段，即使字段是零值
	//db.Save(&user)
	// 根据 `struct` 更新属性，只会更新非零值的字段
	return dao.session().Model(&user).Updates(user).RowsAffected

}

func (dao *SysAccountDao) DelById(ids ...int64) int64 {
	if nil == ids {
		panic("ids can not be nil!")
	}

	return dao.session().Delete(&SysAccount{}, ids).RowsAffected

}

func RunDao() {
	config := OrmConfig{
		DbIp:           "127.0.0.1",
		DbPort:         3306,
		Dbname:         "godbc",
		Username:       "root",
		Password:       "fan1988",
		MaxIdleConns:   10,
		MaxOpenConns:   100,
		ConnectTimeout: 10,
		ShowSql:        true,
	}

	db := initGorm(config).Debug()

	dao := NewSysAccountDao(db)
	user := dao.GetById(10)
	fmt.Println("----------------", user)

}
